package com.tgy.cs;

import com.sun.xml.internal.bind.v2.schemagen.Util;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Objects;

/***
 * @ClassName: CookieDemo1
 * @Description: 学习Cookie
 * @Auther: 送一一块二向箔
 * @Date: 10:14 2021/12/5
 * @version : V1.0
 */
//保存用户上一次访问的时间
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*服务器告诉你来的时间，把这个时间封装成一个信件，你下次带来我就知道是你*/
        //解决中文乱码
        resp.setContentType("text/html; charset=UTF-8");//浏览器显示中文编码
/*        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/
        PrintWriter out = resp.getWriter();
        //cookie 客户端提供，服务器端接收
        Cookie[] cookies = req.getCookies();//可能存在多个Cookie

        //判断Cookie是否存在
        if (cookies!=null) {
            out.write("你上一次访问时间是：");
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(),"LastLoginTime")){
                    /* 获取Cookie的值*/

                    //转换为长整型
                    long l = Long.parseLong(cookie.getValue());
                    //时间戳转化为时间date
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("第一次访问");
        }
        //服务给客户端响应一个Cookie
        Cookie cookie = new Cookie("LastLoginTime", String.valueOf(System.currentTimeMillis()));
        //设置过期时间20秒，感觉和Redis的过期时间有异曲同工之妙
        cookie.setMaxAge(20);
        resp.addCookie(cookie);


    }
}
